{% extends 'layout/manage.html' %}
{% load static %}

{% block title %}
    文件
{% endblock %}

{% block css %}
    <style>
        .error-msg {
            color: red;
            position: absolute;
            font-size: 5px;
        }

        .red_input {
            border: 1px solid red;
        }

        .green_input {
            border: 1px solid green;
        }

        .panel-default .panel-heading {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
        }

        .panel-default > .panel-heading a {
            text-decoration: none;
        }

        .panel-default > .panel-heading span {
            padding: 0 5px;
        }

        .panel-default > .panel-heading .function .upload {
            overflow: hidden;
        }

        .panel-default > .panel-heading .function .upload input {
            opacity: 0;
            position: absolute;
            top: 0;
            bottom: 0;
            width: 76px;
            left: -2px;
            overflow: hidden;
        }

        .upload-progress {
            position: fixed;
            right: 2px;
            bottom: 2px;
            width: 400px;
        }

        .upload-progress .progress-error {
            color: red;
        }
    </style>
{% endblock %}

{% block content %}
    <div class="container-fluid">
        <div class="panel panel-default" style="margin-top: 20px">
            <!-- Default panel contents -->
            <div class="panel-heading">
                <div>

                    <a href="{% url 'file' project_id=request.tracer.project.id %}">
                        <i class="fa fa-home" aria-hidden="true"></i> 文件库</a>
                    <!-- 文件导航-->
                    {% for breadcrumb in breadcrumb_list %}
                        <a href="{% url 'file' project_id=request.tracer.project.id %}?folder={{ breadcrumb.id }}">
                            <i class="fa fa-caret-right" aria-hidden="true"></i><span>{{ breadcrumb.name }}</span>
                        </a>

                    {% endfor %}

                </div>

                <div class="function">
                    <div class="btn btn-primary btn-xs upload" style="position: relative">
                        <div><i class="fa fa-upload" aria-hidden="true"></i> 上传文件</div>
                        <input type="file" multiple name="uploadFile" id="uploadFile">
                    </div>

                    <a class="btn btn-success btn-xs" data-toggle="modal" data-target="#addModal" data-whatever="新建文件夹">
                        <i class="fa fa-plus-circle" aria-hidden="true"></i> 新建文件夹
                    </a>
                </div>
            </div>

            <!-- Table -->
            <table class="table">
                <thead>
                <tr>
                    <th>序号</th>
                    <th>名称</th>
                    <th>文件大小</th>
                    <th>更新者</th>
                    <th>更新时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                {% for item in file_object_list %}
                    <tr>
                        <th scope="row">{{ forloop.counter }}</th>
                        <td>
                            {% if item.file_type == 1 %}
                                <i class="fa fa-file" aria-hidden="true"></i>
                                {{ item.name }}

                            {% else %}
                                <!--有就一直渲染-->
                                <a href="{% url 'file' project_id=request.tracer.project.id %}?folder={{ item.id }}">
                                    <i class="fa fa-folder" aria-hidden="true">
                                    </i> {{ item.name }}
                                </a>
                            {% endif %}
                        </td>
                        <td>
                            {% if item.file_type == 1 %}
                                {{ item.file_size }}
                            {% else %}
                                --
                            {% endif %}
                        </td>
                        <td>{{ item.update_user.username }}</td>
                        <td>{{ item.update_datetime }}</td>
                        <td>
                            {% if item.file_type == 2 %}
                                <a class="btn btn-primary btn-xs"
                                   data-toggle="modal"
                                   data-target="#addModal"
                                   data-fid="{{ item.id }}"
                                   data-name="{{ item.name }}"
                                   data-whatever="编辑文件夹">
                                    <i class="fa fa-pencil-square-o" aria-hidden="true">编辑</i>
                                </a>
                            {% else %}
                                <a class="btn btn-default btn-xs download"
                                   href="{% url 'file_download' project_id=request.tracer.project.id file_id=item.id %}">
                                    <i class="fa fa-cloud-download" aria-hidden="true">下载</i>
                                </a>
                            {% endif %}
                            <a class="btn btn-danger btn-xs"
                               data-toggle="modal"
                               data-fid="{{ item.id }}"
                               data-target="#alertModal">
                                <i class="fa fa-trash" aria-hidden="true">删除</i>
                            </a>
                        </td>

                    </tr>
                {% endfor %}


                </tbody>
            </table>
        </div>
        <!--添加文件夹Model-->
        <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="myModalLabel"></h4>
                    </div>
                    <div class="modal-body">
                        <form id="form">{% csrf_token %}
                            <!--把id传到后端，用作区分是编辑还是新增-->
                            <input class="hide" type="text" name="fid" id="fid">
                            {% for field in form %}
                                <div class="form-group">
                                    <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                                    {{ field }}
                                    <span class="error-msg">{{ field.errors.0 }}</span>
                                </div>
                            {% endfor %}
                        </form>

                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">取 消</button>
                        <button id="btnFormSubmit" type="button" class="btn btn-primary">确 定</button>
                    </div>
                </div>
            </div>
        </div>

        <!--删除模态框+警告框-->
        <div class="modal fade" id="alertModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <div class="modal-dialog" role="document">

                <div class="alert alert-danger alert-dismissible fade in" role="alert">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">×</span></button>
                    <h4>是否要确定删除？</h4>
                    <p style="padding-top: 20px;padding-bottom: 20px;">
                        文件夹中包含的所有的文件都会被删除。
                    </p>
                    <p style="text-align: right">
                        <a href="" class="btn btn-default" data-dismiss="modal" aria-label="Close">取消</a>
                        <button type="button" class="btn btn-danger" id="btnDelete">确认</button>
                    </p>
                </div>

            </div>
        </div>
    </div>

    <!--上传-->
    <div id="uploadProgress" class="upload-progress hide">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <i class="fa fa-cloud-upload" aria-hidden="true"></i> 上传进度
            </div>

            <table class="table">
                <tbody id="progressList">

                </tbody>
            </table>
        </div>
    </div>
    <!--上传动态展示-->
    <div class="hide">
        <table id="progressTemplate">
            <tr>
                <td>
                    <div class="name"></div>
                    <div class="progress">
                        <div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar"
                             aria-valuenow="0"
                             aria-valuemin="0"
                             aria-valuemax="100" style="width: 0%;">
                            0%
                        </div>
                    </div>
                    <div class="progress-error"></div>
                </td>
            </tr>
        </table>
    </div>
    <!--上传成功以后展示-->
    <div class="hide">
        <table id="rowTpl">
            <tr>
                <td>
                    <i class="fa fa-file" aria-hidden="true"></i>
                    <span class="name"></span>
                </td>
                <td class="file_size"></td>
                <td class="username"></td>
                <td class="datetime"></td>
                <td>

                    <a class="btn btn-default btn-xs download">
                        <i class="fa fa-cloud-download" aria-hidden="true"></i>
                    </a>

                    <a class="btn btn-danger btn-xs delete" data-toggle="modal" data-target="#alertModal">
                        <i class="fa fa-trash" aria-hidden="true"></i>
                    </a>
                </td>
            </tr>
        </table>
    </div>

{% endblock %}



{% block js %}
    <script src="{% static 'js/cos-js-sdk-v5.min.js' %}"></script>
    <script>
        var FOLDER_URL = "{% url 'file' project_id=request.tracer.project.id %}";
        var FOLDER_DELETE_URL = "{% url 'file_delete' project_id=request.tracer.project.id %}";
        var COS_CREDENTIAL = "{% url 'cos_credential' project_id=request.tracer.project.id %}";
        var FILE_POST = "{% url 'file_post' project_id=request.tracer.project.id %}";
        var CURRENT_FOLDER_ID = "{{ parent_obj.id }}";

        $(function () {
            initAddModel();
            initalertModel();
            bindModelSubmit();
            bindDeleteSubmit();

            bindUploadFile();

        })

        // 动态改变模态框的title
        function initAddModel() {
            $('#addModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget)
                var recipient = button.data('whatever')
                var fid = button.data('fid')
                var name = button.data('name')

                var modal = $(this)
                modal.find('.modal-title').text(recipient)
                modal.find('.error-msg').text('')
                // 编辑
                if (fid) {

                    // 隐藏的input框
                    modal.find('#fid').val(fid)
                    modal.find('#id_name').val(name)
                } else {
                    // 转doqument对象 编辑
                    $('#form')[0].reset();
                    $('#id_name').removeClass('red_input');
                }


            })


        }

        // 动态删除
        function initalertModel() {
            $('#alertModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget); // Button that triggered the modal
                var fid = button.data('fid'); // Extract info from data-* attributes
                $('#btnDelete').attr('fid', fid);

            })
        }

        // 文件夹新增ajax
        function bindModelSubmit() {
            $('#btnFormSubmit').click(
                function () {
                    $.ajax({
                        url: location.href,
                        type: "POST",
                        data: $('#form').serialize(),
                        dataType: "JSON",
                        success: function (res) {
                            if (res.status) {
                                window.location.reload();
                            } else {
                                // 错误信息渲染 {mobile_phone: ['手机号格式错误！']}
                                // 错误时当前input框变红
                                $.each(res.msg, function (key, value) {
                                    $('#id_' + key).addClass('red_input').next().text(value[0])
                                    // attr 只有添加的一个属性 其他的全部消失 addClass 在原有的基础上添加类
                                })
                            }

                        }
                    })
                    // 获取焦点 input红框消失 this： 当前操作的对象
                    $('input').focus(function () {
                        $(this).removeClass('red_input').next().empty()
                    })
                }
            )
        }

        // 文件夹/文件删除ajax
        function bindDeleteSubmit() {
            $('#btnDelete').click(
                function () {
                    $.ajax({
                        url: FOLDER_DELETE_URL,
                        type: "GET",
                        data: {fid: $('#btnDelete').attr('fid')},
                        dataType: "JSON",
                        success: function (res) {
                            if (res.status) {
                                window.location.reload();

                            }

                        }
                    })

                }
            )
        }

        // 上传文件/获取凭证/写入数据库/展示进度
        function bindUploadFile() {
            $('#uploadFile').change(function () {
                $('#progressList').empty();

                var fileList = $(this)[0].files;
                // 获取本次要上传的每个文件 名称&大小
                var checkFileList = [];
                $.each(fileList, function (index, fileObject) {
                    checkFileList.push({'name': fileObject.name, 'size': fileObject.size})
                });

                // 把这些数据发送到django后台：Django后台进行容量的校验，如果么有问题则返回临时凭证；否则返回错误信息；
                var cos_credential = new COS({
                    getAuthorization: function (options, callback) {
                        $.post(COS_CREDENTIAL, JSON.stringify(checkFileList), function (res) {
                            if (res.status) {
                                var credentials = res.data && res.data.credentials;
                                // 凭证
                                callback({
                                    TmpSecretId: credentials.tmpSecretId,
                                    TmpSecretKey: credentials.tmpSecretKey,
                                    XCosSecurityToken: credentials.sessionToken,
                                    StartTime: res.data.startTime,
                                    ExpiredTime: res.data.expiredTime
                                });

                                $('#uploadProgress').removeClass('hide');
                            } else {
                                alert(res.error);
                            }
                        });
                    }
                });

                // 上传文件（上传之前先获取临时凭证）
                $.each(fileList, function (index, fileObject) {
                    var fileName = fileObject.name;
                    var fileSize = fileObject.size;
                    var key = (new Date()).getTime() + "_" + fileName;

                    var tr = $('#progressTemplate').find('tr').clone();
                    tr.find('.name').text(fileName);
                    $('#progressList').append(tr);

                    // 上传文件（异步）
                    cos_credential.putObject({
                        Bucket: '{{ request.tracer.project.bucket }}', /* 必须 */
                        Region: '{{ request.tracer.project.region }}', /* 存储桶所在地域，必须字段 */
                        Key: key, /* 必须 */
                        Body: fileObject, // 上传文件对象
                        onProgress: function (progressData) {
                            var percent = progressData.percent * 100 + '%';
                            tr.find('.progress-bar').text(percent);
                            tr.find('.progress-bar').css('width', percent);
                        }
                    }, function (err, data) {
                        if (data && data.statusCode === 200) {
                            // 上传成功，将本次上传的文件提交到后台并写入数据
                            // 当前文件上传成功
                            $.post(FILE_POST, {
                                name: fileName,
                                key: key,
                                file_size: fileSize,
                                parent: CURRENT_FOLDER_ID,
                                etag: data.ETag,
                                file_path: data.Location
                            }, function (res) {
                                // 在数据库中写入成功，将已添加的数据在页面上动态展示。
                                var newTr = $('#rowTpl').find('tr').clone();
                                newTr.find('.name').text(res.data.name);
                                newTr.find('.file_size').text(res.data.file_size);
                                newTr.find('.username').text(res.data.username);
                                newTr.find('.datetime').text(res.data.datetime);
                                newTr.find('.delete').attr('data-fid', res.data.id);
                                newTr.find('.download').attr('href', res.data.download_url);
                                $('#rowList').append(newTr);

                                // 自己的进度删除
                                tr.remove();
                                window.location.reload();

                            })

                        } else {
                            tr.find('.progress-error').text('上传失败');
                        }
                    });


                })
            });
        }

    </script>
{% endblock %}